<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\Request;
use think\facade\Db;

class Postcate extends Base
{
    protected $middleware = [
        '\app\admin\middleware\LoginCheck',
        '\app\admin\middleware\UrlData',
        '\app\admin\middleware\UrlCheck'

    ];

    //论坛分类控制器
    public function index() //分类列表
    {

        return view();
    }

    public function data($limit,$page)  //列表数据
    {
        $offset = ($page-1)*$limit;
        $limit = (int)$limit;

        $list = Db::table('post_cate')
            ->where('status','<>',2)
            ->limit($offset,$limit)
            ->select()->toArray();

        $count = Db::table('post_cate')->count();

        return json([
            "code"=>0,
            "msg"=>"",
            "count"=>$count,
            "data"=>$list
        ]);
    }


    public function update()    //分类修改
    {
        if($this->request->isPost()){
            $data = $this->request->post();

            $cate_logo = $this->haveUpFile('cate_logo',$_FILES);

            if($cate_logo){
                $data['cate_logo'] = $cate_logo;
            }


            $data['update_time'] = date("Y-m-d H:i:s");
            $res = Db::table('post_cate')->update($data);

            if($res){
                $this->success('分类修改成功','index');
            }
            $this->error('分类修改失败');
        }

        $id = $this->request->get('id');
        $list = Db::table('post_cate')->where('id',$id)->field('id,cate_name,cate_introduce,cate_logo,status')->find();


        return view('add',['list'=>$list]);
    }

    public function add()   //分类添加
    {
        if($this->request->isPost()){   //如果是添加
            $data = $this->request->post();

            $file = request()->file('cate_logo');
            //存储文件
            $cate_logo = \think\facade\Filesystem::disk('public')->putFile( 'cate_logo', $file);
            $cate_logo = "/storage/".$cate_logo;

            $data['cate_logo'] = $cate_logo;

            $data = $this->insertTime($data);   //加入时间

            $res = Db::table('post_cate')->save($data);     //存入数据
            if($res){
                $this->success('分类添加成功','index');
            }
            $this->error('分类添加失败');
        }


        return view();
    }

    public function delete()    //分类删除
    {
        if($this->request->isPost()){
            $id = $this->request->post('id');

            $res = Db::table('post_cate')->where('id',$id)->update(['status' => '2']);

            if($res){
                return json([
                    'code'=>200,
                    'msg'=>'删除成功'
                ]);
            }
            return json([
                'code'=>400,
                'msg'=>'删除失败'
            ]);
        }
    }






}

